import { message } from 'antd'
import request, { extend } from 'umi-request';
import {IFormProps} from '../models/data'

const errorHandler = function(error: any) {
  if (error.response) {
    // console.log(error.response.status);
    // console.log(error.response.headers);
    // console.log(error.data);
    // console.log(error.request);
    if (error.response.status > 400) {
        message.error(error.data.message ? error.data.message : error.data)
    }
  } else {
    // The request was made but no response was received or error occurs when setting up the request.
    // console.log(error.message);
    message.error('network error')
  }
  throw error;
};

// 1. Unified processing
const extendRequest = extend({ errorHandler });

// 获取数据的请求函数
export const getRemoveList = async({page, per_page}:{page: number, per_page: number}) => {
    return extendRequest(`/api/users?page=${page}&per_page=${per_page}`, {
        method: 'get',
    })
    .then((response) => {
        return response
    })
    .catch((error) => {
        return false
    });
}

// 修改数据的请求函数
export const editRecord = async(values: IFormProps, id: number) => {
    return extendRequest('/api/users/'+id, {
        method: 'put',
        data: values
    })
    .then((response) => {
        return true
    })
    .catch((error) => {
        return false
    });
}

// 添加数据的请求函数
export const addRecord = async(values: IFormProps, id?: number) => {
    return extendRequest('/api/users', {
        method: 'post',
        data: values
    })
    .then((response) => {
        return true
    })
    .catch((error) => {
        return false
    });
}